<template>
  <div class="app-container">
    <!--工具栏-->
    <el-form ref="queryForm" :inline="true" :model="query" label-width="100px">
      <el-form-item label="商品名称">
        <el-input
          v-model="query.goodsName"
          clearable
          placeholder="请输入商品名称"
          size="small"
          @keyup.enter.native="toQuery"
        />
      </el-form-item>
      <el-form-item label="选择时间">
        <el-date-picker
          v-model="queryDateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="商品分类">
        <el-cascader
          v-model="query.cateId"
          :options="goodsCateList"
          :props="{ checkStrictly: true, value: 'id', emitPath: false }"
          clearable
          placeholder="选择商品分类"
        />
      </el-form-item>
      <el-form-item>
        <el-button v-has-permission="['pms:goods:list']" icon="el-icon-search" size="mini" type="success" @click="toQuery">搜索</el-button>
        <el-button
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          @click="add"
        >发布商品</el-button>
        <el-button
          class="filter-item"
          size="mini"
          type="info"
          icon="el-icon-download"
          @click="exportGoodsInfo"
        >导出商品</el-button>
        <el-button
          type="danger"
          class="filter-item"
          size="mini"
          icon="el-icon-refresh"
          @click="resetQuery"
        >刷新</el-button>
      </el-form-item>
    </el-form>

    <!--表格渲染-->
    <el-table v-loading="loading" :data="data" style="width: 100%;">
      <el-table-column prop="id" label="货号">
        <template slot-scope="scope">
          <span>No.{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column ref="table" prop="image" label="商品图片">
        <template slot-scope="scope">
          <el-image :src="scope.row.image" class="el-avatar" :preview-src-list="[scope.row.image]">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline" />
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column prop="productName" label="商品名称" />
      <el-table-column prop="category.cateName" label="分类名称" />
      <el-table-column prop="otPrice" label="商品原价" />
      <el-table-column prop="price" label="商品现价" />
      <el-table-column label="代理售价" width="180">
        <template slot-scope="scope">
          <span v-for="item in scope.row.memberPrice" :key="item.id">
            <span style="color: #dd1100">{{ item.memberLevelName }}售价: {{ item.memberPrice }}</span><br>
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="stock" label="库存" />
      <el-table-column prop="sales" label="销量" />
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column label="状态" align="center" width="160">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isShow"
            loading
            active-text="上架"
            inactive-text="下架"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          /></template>
      </el-table-column>
      <el-table-column label="操作" width="205px" align="center">
        <template slot-scope="scope">
          <el-dropdown size="mini" split-button type="primary" trigger="click">
            操作
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-button
                  size="mini"
                  style="width: 100%; margin: 5px 0"
                  plain
                  type="primary"
                  icon="el-icon-edit"
                  @click="edit(scope.row)"
                >编辑</el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-button
                  size="mini"
                  style="width: 100%; margin: 5px 0"
                  plain
                  type="success"
                  icon="el-icon-edit"
                  @click="editStock(scope.row)"
                >调整库存</el-button>
              </el-dropdown-item>
              <el-dropdown-item>
                <el-popover
                  :ref="scope.row.id"
                  placement="top"
                  width="180"
                >
                  <p>确定删除本条数据吗？</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
                    <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.id)">确定</el-button>
                  </div>
                  <el-button slot="reference" style="width: 100%; margin: 5px 0" plain type="danger" icon="el-icon-delete" size="mini">删除</el-button>
                </el-popover>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <el-pagination
      :total="total"
      :current-page="page"
      style="margin-top: 8px;"
      layout="total, prev, pager, next, sizes"
      @size-change="sizeChange"
      @current-change="pageChange"
    />
    <!-- 添加或修改活动对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.visible" width="40%" append-to-body>
      <el-form ref="stockForm" :model="stockForm" label-width="100px">
        <el-form-item label="当前库存" prop="stock">
          <el-input-number v-model="stockForm.stock" :min="0" disabled />
        </el-form-item>
        <el-form-item label="操作" prop="type">
          <el-radio-group v-model="stockForm.type" style="width: 178px">
            <el-radio :label="1">新增</el-radio>
            <el-radio :label="0">减少</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="数量" prop="num">
          <el-input-number v-model="stockForm.num" :min="0" :max="99999999" :precision="0" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitStockForm">确 定</el-button>
        <el-button @click="cancelStockForm">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import checkPermission from '@/utils/permission'
import initData from '@/mixins/crud'
import {del, editGoodsStock, exportGoodsInfo, onsale} from '@/api/pms/yxStoreProduct'
import { getCates } from '@/api/pms/yxStoreCategory'
import {downloadFile} from "@/utils";

export default {
  components: { },
  mixins: [initData],
  data() {
    return {
      showSearch: true,
      delLoading: false,
      queryDateRange: undefined,
      visible: false,
      goodsCateList: [],
      stockForm: {
        goodsId: undefined,
        num: 0,
        stock: 0,
        type: 1
      },
      dialog: {
        title: undefined,
        visible: false,
        type: undefined // type 操作类型：1-新增 2-修改
      }
    }
  },
  created() {
    this.$nextTick(() => {
      this.init()
      this.getGoodsCateList()
    })
  },
  methods: {
    checkPermission,
    beforeInit() {
      this.url = 'admin/api/yxStoreProduct'
      const sort = 'id,desc'
      this.params = { sort: sort, isShow: 1 }
      const goodsName = this.query.goodsName
      if (goodsName) {
        this.params['goodsName'] = goodsName
      }
      const dateRange = this.queryDateRange
      if (dateRange) {
        this.params['startTime'] = dateRange[0]
        this.params['endTime'] = dateRange[1]
      }
      const cateId = this.query.cateId
      if (cateId) {
        this.params['cateId'] = cateId
      }
      return true
    },
    resetQuery() {
      this.query = { }
      this.init()
    },
    getGoodsCateList() {
      getCates({ enabled: true }).then(res => {
        this.goodsCateList = res.data.list
      })
    },
    subDelete(id) {
      this.delLoading = true
      del(id).then(res => {
        this.delLoading = false
        this.$refs[id].doClose()
        this.dleChangePage()
        this.init()
        this.$notify({
          title: '删除成功',
          type: 'success',
          duration: 2500
        })
      }).catch(err => {
        this.delLoading = false
        this.$refs[id].doClose()
        console.log(err.data.message)
      })
    },
    handleStatusChange(val) {
      this.onSale(val.id, val.isShow)
    },
    onSale(id, status) {
      this.$confirm(`确定进行[${status ? '上架' : '下架'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          onsale(id, { status: status }).then(({ data }) => {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.init()
              }
            })
          })
        })
        .catch(() => {
          this.init()
        })
    },
    add() {
      // this.isAdd = true
      // this.$refs.form.dialog = true
      // this.$refs.form.getCates()
      this.$router.push({
        path: 'add',
        query: {
          isAdd: 'true'
        }
      })
    },
    edit(data) {
      this.$router.push({
        path: 'edit',
        query: {
          isAdd: 'false',
          goodsId: data.id
        }
      })
    },
    editStock(val) {
      this.stockForm.goodsId = val.id
      this.stockForm.stock = val.stock
      this.dialog = {
        title: '调整库存',
        visible: true
      }
    },
    submitStockForm() {
      editGoodsStock(this.stockForm).then(res => {
        this.$message({
          message: res.message,
          type: 'success'
        })
        this.cancelStockForm()
        this.resetQuery()
      })
    },
    cancelStockForm() {
      this.dialog = {
        title: undefined,
        visible: false
      }
      this.stockForm = {
        goodsId: undefined,
        num: 0,
        stock: 0,
        type: 1
      }
    },
    exportGoodsInfo() {
      this.$confirm('是否确认导出所有商品数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return exportGoodsInfo({ isShow: 1 })
      }).then(response => {
        downloadFile(response.data, '上架商品列表', 'xls')
      })
    }
  }
}
</script>

<style scoped>

</style>
